package com.platform.user.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.platform.bean.JsonResult;
import com.platform.bean.PageInfo;
import com.platform.user.dao.ItemApplyDao;
import com.platform.user.dao.ItemClaimNoticeDao;
import com.platform.user.dao.LostHelpNoticeDao;
import com.platform.user.dao.UserDao;
import com.platform.user.dto.ApplyItemNoticeDto;
import com.platform.user.dto.ApplyItemUserDto;
import com.platform.user.dto.AuditItemNoticeDto;
import com.platform.user.dto.ChatRoomEnterApplicationDto;
import com.platform.user.entity.*;
import com.platform.utils.Base64Utils;
import com.platform.utils.PrintMessageUtils;
import com.platform.utils.UploadFileToRemoteUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
public class ItemApplyService {

    @Resource
    private ItemApplyDao itemApplyDao;
    @Resource
    private LostHelpNoticeDao lostHelpNoticeDao;
    @Resource
    private ItemClaimNoticeDao itemClaimNoticeDao;
    @Resource
    private UserDao userDao;

    public List<ApplyItemUserDto> publisherUserQueryApplyItemList(Map<String, Object> params) {
        PrintMessageUtils.traverseMap(params);
        params.put("applyStatus", 0);
//        List<ChatRoomEnterApplication> chatRoomEnterApplicationList = chatRoomEnterApplicationDao.queryListByParams(params);
        List<ApplyItemUserDto> applyItemUserDtoList = new ArrayList<>();
        List<ItemApply> itemApplyList = itemApplyDao.queryListByParams(params);
        for (ItemApply x: itemApplyList) {
            ApplyItemUserDto applyItemUserDto = new ApplyItemUserDto();
            applyItemUserDto.setItemApply(x);
            User user = userDao.queryById(x.getApplicantUserId());
            user.setFullName(null);
            user.setEmail(null);
            user.setPassword(null);
            applyItemUserDto.setUser(user);
            applyItemUserDtoList.add(applyItemUserDto);
        }
        return applyItemUserDtoList;
    }

    public void deleteApply(Map<String, Object> params) {
        int id = Integer.parseInt(params.get("itemApplyId").toString());
        ItemApply itemApply = itemApplyDao.queryById(id);
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("itemId", itemApply.getItemId());
        queryParams.put("itemSort", itemApply.getItemSort());
        queryParams.put("applyStatus", itemApply.getApplyStatus());
        List<ItemApply> itemApplyList = itemApplyDao.queryListByParams(queryParams);
        if (itemApplyList != null && itemApplyList.size() == 1) {
            if (itemApply.getItemSort() == 0) {
                LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(itemApply.getItemId());
                lostHelpNotice.setItemStatus(1);
                lostHelpNoticeDao.update(lostHelpNotice);
            } else {
                ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(itemApply.getItemId());
                itemClaimNotice.setItemStatus(1);
                itemClaimNoticeDao.update(itemClaimNotice);
            }
        }
        itemApplyDao.deleteById(id);
    }

    public void updateApply(Map<String, Object> params) {
        int id = Integer.parseInt(params.get("itemApplyId").toString());
        String applyDetail = params.get("applyDetail").toString();
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> imageFileList = (List<Map<String, Object>>) params.get("imageFileList");
        ItemApply itemApply = itemApplyDao.queryById(id);

        List<String> oldImageUrlList = new ArrayList<>();
        List<String> newImageUrlList = new ArrayList<>();

        // 找到老的图片
        if (itemApply.getApplyImage1() != null) {
            oldImageUrlList.add(itemApply.getApplyImage1());
        }
        if (itemApply.getApplyImage2() != null) {
            oldImageUrlList.add(itemApply.getApplyImage2());
        }
        if (itemApply.getApplyImage3() != null) {
            oldImageUrlList.add(itemApply.getApplyImage3());
        }

        // 更新新的图片
        try {
            if (!imageFileList.isEmpty() && imageFileList.get(0) != null) {
                String imgUrl = processBase64ToUrl(imageFileList.get(0).get("url").toString());
                newImageUrlList.add(imgUrl);
                itemApply.setApplyImage1(imgUrl);
            } else {
                itemApply.setApplyImage1(null);
            }

            if (imageFileList.size() > 1 && imageFileList.get(1) != null) {
                String imgUrl = processBase64ToUrl(imageFileList.get(1).get("url").toString());
                newImageUrlList.add(imgUrl);
                itemApply.setApplyImage2(imgUrl);
            } else {
                itemApply.setApplyImage2(null);
            }

            if (imageFileList.size() > 2 && imageFileList.get(2) != null) {
                String imgUrl = processBase64ToUrl(imageFileList.get(2).get("url").toString());
                newImageUrlList.add(imgUrl);
                itemApply.setApplyImage3(imgUrl);
            } else {
                itemApply.setApplyImage3(null);
            }

        } catch (Exception e) {
            for (String x: newImageUrlList) {
                deleteImageByUrl(x);
            }
            e.printStackTrace();
        }

        // 删除旧图片
        for (String x: oldImageUrlList) {
            deleteImageByUrl(x);
        }
        itemApply.setApplyDetail(applyDetail);
        itemApply.setApplyStatus(0);
        itemApply.setCreatedTime(new Date());
        itemApplyDao.update(itemApply);

        if (itemApply.getItemSort() == 0) {
            LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(itemApply.getItemId());
            lostHelpNotice.setItemStatus(2);
            lostHelpNoticeDao.update(lostHelpNotice);
        } else {
            ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(itemApply.getItemId());
            itemClaimNotice.setItemStatus(2);
            itemClaimNoticeDao.update(itemClaimNotice);
        }
    }

    public void withdrawApply(Map<String, Object> params) {
        int id = Integer.parseInt(params.get("itemApplyId").toString());
        ItemApply itemApply = itemApplyDao.queryById(id);
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("itemId", itemApply.getItemId());
        queryParams.put("itemSort", itemApply.getItemSort());
        queryParams.put("applyStatus", itemApply.getApplyStatus());
        List<ItemApply> itemApplyList = itemApplyDao.queryListByParams(queryParams);
        if (itemApplyList != null && itemApplyList.size() == 1) {
            if (itemApply.getItemSort() == 0) {
                LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(itemApply.getItemId());
                lostHelpNotice.setItemStatus(1);
                lostHelpNoticeDao.update(lostHelpNotice);
            } else {
                ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(itemApply.getItemId());
                itemClaimNotice.setItemStatus(1);
                itemClaimNoticeDao.update(itemClaimNotice);
            }
        }
        itemApply.setApplyStatus(1);
        itemApplyDao.update(itemApply);
    }

    public PageInfo<ApplyItemNoticeDto> applicantUserQueryApplyItemByPage(Map<String, Object> params) {

        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Page<Map> page = new Page<>(pageIndex, pageSize);

//        List<ItemAudit> itemAuditList = itemAuditDao.queryByPage(page, params);
        List<ApplyItemNoticeDto> applyItemNoticeDtoList = new ArrayList<>();
        List<ItemApply> itemApplyList = itemApplyDao.queryByPage(page, params);

        for (ItemApply x: itemApplyList) {
            ApplyItemNoticeDto applyItemNoticeDto = new ApplyItemNoticeDto();
            if (x.getItemSort() == 0) {
                LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(x.getItemId());
                applyItemNoticeDto.setLostHelpNotice(lostHelpNotice);
            } else {
                ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(x.getItemId());
                applyItemNoticeDto.setItemClaimNotice(itemClaimNotice);
            }
            applyItemNoticeDto.setItemApply(x);
            applyItemNoticeDto.setApplyStatus(x.getApplyStatus());
            applyItemNoticeDto.setItemSort(x.getItemSort());
            applyItemNoticeDtoList.add(applyItemNoticeDto);
        }
        // PrintMessageUtils.traverseList(lostHelpNoticeList);
        return new PageInfo<>(pageIndex, pageSize, itemApplyDao.countByParams(params), applyItemNoticeDtoList);
    }

    public int queryUserIfApply(Map<String, Object> params) {
        Integer itemId = Integer.parseInt(params.get("itemId").toString());
        Integer itemSort = Integer.parseInt(params.get("itemSort").toString());
        Integer applicantUserId = Integer.parseInt(params.get("applicantUserId").toString());
        ItemApply itemApply = itemApplyDao.queryOneByParams(params);
        if (itemApply != null) {
            return 0;
        }
        return 1;
    }

    public int addItemApply(Map<String, Object> params) throws IOException {
        Integer applicantUserId = Integer.parseInt(params.get("applicantUserId").toString());
        Integer itemId = Integer.parseInt(params.get("itemId").toString());
        Integer itemSort = Integer.parseInt(params.get("itemSort").toString());
        String applyDetail = params.get("applyDetail").toString();
        Integer publisherUserId = Integer.parseInt(params.get("publisherUserId").toString());
        String itemName = params.get("itemName").toString();
        params.put("applyStatus", 0);
        ItemApply existItemApply = itemApplyDao.queryOneByParams(params);

        if (existItemApply != null) {
            return 0;
        }

        List<String> newImageUrlList = new ArrayList<>();
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> imageFileList = (List<Map<String, Object>>) params.get("imageFileList");

        ItemApply itemApply = new ItemApply();
        itemApply.setApplyStatus(0);
        itemApply.setApplyDetail(applyDetail);
        itemApply.setItemSort(itemSort);
        itemApply.setCreatedTime(new Date());
        itemApply.setItemId(itemId);
        itemApply.setPublisherUserId(publisherUserId);
        itemApply.setItemName(itemName);
        itemApply.setApplicantUserId(applicantUserId);

        try {
            if (!imageFileList.isEmpty() && imageFileList.get(0) != null) {
                String imgUrl = processBase64ToUrl(imageFileList.get(0).get("url").toString());
                newImageUrlList.add(imgUrl);
                itemApply.setApplyImage1(imgUrl);
            }

            if (imageFileList.size() > 1 && imageFileList.get(1) != null) {
                String imgUrl = processBase64ToUrl(imageFileList.get(1).get("url").toString());
                newImageUrlList.add(imgUrl);
                itemApply.setApplyImage2(imgUrl);
            }

            if (imageFileList.size() > 2 && imageFileList.get(2) != null) {
                String imgUrl = processBase64ToUrl(imageFileList.get(2).get("url").toString());
                newImageUrlList.add(imgUrl);
                itemApply.setApplyImage3(imgUrl);
            }

            itemApplyDao.insert(itemApply);

        } catch (Exception e) {
            for (String x: newImageUrlList) {
                deleteImageByUrl(x);
            }
            e.printStackTrace();
        }

        if (itemSort == 0) {
            LostHelpNotice lostHelpNotice = lostHelpNoticeDao.queryById(itemId);
            lostHelpNotice.setItemStatus(2);
            lostHelpNoticeDao.update(lostHelpNotice);
        } else {
            ItemClaimNotice itemClaimNotice = itemClaimNoticeDao.queryById(itemId);
            itemClaimNotice.setItemStatus(2);
            itemClaimNoticeDao.update(itemClaimNotice);
        }
        return 1;
    }

    /**
     * 根据url删除图片
     *
     * @param url 图片url
     */
    private void deleteImageByUrl(String url) {
        if (url != null) {
            UploadFileToRemoteUtils.deleteFileFromRemoteServer(url,
                    "/opt/docker/apache/www/images/lost_and_found");
        }
    }

    /**
     * 将base64封面图片转换为url
     *
     * @param imageBase64 base64图片
     * @return 图片url
     * @throws IOException 异常
     */
    private String processBase64ToUrl(String imageBase64) throws IOException {
        StringBuilder fileName = new StringBuilder();
        Map<String, String> imageTypeAndCode = Base64Utils.splitImageTypeAndCode(imageBase64);
        String imageType = null;
        String base64Data = null;

        if (imageTypeAndCode != null) {
            imageType = imageTypeAndCode.get("imageType");
            base64Data = imageTypeAndCode.get("base64Data");
        }

        fileName.append(System.currentTimeMillis()).append(".").append(imageType);
        // Base64转文件
        MultipartFile multipartFile = Base64Utils.convertBase64ToMultipart(base64Data, fileName.toString());
        JsonResult jsonResult = UploadFileToRemoteUtils.uploadFileToRemoteServer(multipartFile, "/opt/docker/apache/www/images/lost_and_found");
        return (String) jsonResult.getData();
    }
}
